/**
 * ======================================
 * 所有登录的逻辑
 * author: sky52
 * file: main.js
 * date: 2022/7/10 22:53
 * ======================================
 */
import QRCode from 'qrcodejs2'
import { getCode, scanCode } from '@/api/user'
import { getLoginTypeName, setLoginType } from '@/utils/common'
import { setToken } from '@/utils/auth'
import LoginForm from './components/login-form'

export default {
  name: 'Login',
  components: { LoginForm },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入账号'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能少于6位'))
      } else {
        callback()
      }
    }
    return {
      // 监管端1，楼宇端2，企业端3
      type: 3,
      title: '',
      loginForm: {
        type: 3,
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      isScan: false,
      scanCode: '',
      timer: null
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    setLoginType(this.type)
    this.title = getLoginTypeName()
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.loginForm.type = this.type
          setLoginType(this.type)
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    changeWay() {
      this.isScan = !this.isScan
      if (this.isScan) {
        this.getCodeInfo()
      }
    },
    getCodeInfo() {
      const params = {}
      getCode(params).then(res => {
        if (res.msg === 'succeed') {
          this.scanCode = res.data.code
          this.$refs.qrcode.innerHTML = ''
          new QRCode(this.$refs.qrcode, {
            width: 200,
            height: 200,
            text: 'https://data.citylaboratory.cn/authorize?code=' + this.scanCode
          })
          if (this.timer) {
            console.log('我也调用了')
            clearInterval(this.timer)
          }
          this.timer = setInterval(() => {
            console.log('执行到')
            this.userScan()
          }, 1000)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    refreshCode() {
      this.getCodeInfo()
    },
    userScan() {
      const that = this
      const params = { code: this.scanCode }
      console.log('调用我')
      scanCode(params).then(res => {
        if (res.msg === 'succeed') {
          if (res.data.status === 3) {
            console.log('调用我来，我只要跳转孩子选哪个的')
            clearInterval(that.timer)
            const token = res.data.token
            that.$store.commit('SET_TOKEN', token)
            setToken(token)
            that.$router.push({ path: that.redirect || '/' })
          }
        }
      }).catch(err => {
        clearInterval(this.timer)
        console.log(err)
      })
    }
  }
}
